from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4PromotionInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4PromotionInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class PromotionInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()
	
	def isTerrainDefenseDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(gc.getNumTerrainInfos()):
			if(objPromotionInfo.getTerrainDefensePercent(iI) > 0):
				return true
				
		return false
	
	def isFeatureDefenseDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(gc.getNumFeatureInfos()):
			if(objPromotionInfo.getFeatureDefensePercent(iI) > 0):
				return true
				
		return false
	
	def isUnitCombatModifierDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(gc.getNumUnitCombatInfos()):
			if(objPromotionInfo.getUnitCombatModifierPercent(iI) > 0):
				return true
				
		return false

	def isDomainModifierDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(DomainTypes.NUM_DOMAIN_TYPES):
			if(objPromotionInfo.getDomainModifierPercent(iI) > 0):
				return true
				
		return false
				
	def isTerrainDoubleMoveDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(gc.getNumTerrainInfos()):
			if(objPromotionInfo.getTerrainDoubleMove(iI)):
				return true
				
		return false
				
	def isFeatureDoubleMoveDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(gc.getNumFeatureInfos()):
			if(objPromotionInfo.getFeatureDoubleMove(iI)):
				return true
				
		return false
				
	def isUnitCombatDefined(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		for iI in range(gc.getNumUnitCombatInfos()):
			if(objPromotionInfo.getUnitCombat(iI)):
				return true
				
		return false
				
	def printPromotion(self, iPromotion):
		objPromotionInfo = gc.getPromotionInfo(iPromotion)

		szText = ""
		
		szText = appendString(szText,"		<PromotionInfo>")
		szText = appendString(szText,"			<Type>%s</Type>" %(objPromotionInfo.getType()))
		szText = appendString(szText,"			<Description>%s</Description>" %(objPromotionInfo.getTextKey()))
		szText = appendString(szText,"			<Sound>%s</Sound>" %(objPromotionInfo.getSound()))

		if(objPromotionInfo.getPrereqPromotion() != -1):
			szText = appendString(szText,"			<PromotionPrereq>%s</PromotionPrereq>" %(gc.getPromotionInfo(objPromotionInfo.getPrereqPromotion()).getType()))
		else:
			szText = appendString(szText,"			<PromotionPrereq>NONE</PromotionPrereq>")

		if(objPromotionInfo.getPrereqOrPromotion1() != -1):
			szText = appendString(szText,"			<PromotionPrereqOr1>%s</PromotionPrereqOr1>" %(gc.getPromotionInfo(objPromotionInfo.getPrereqOrPromotion1()).getType()))
		else:
			szText = appendString(szText,"			<PromotionPrereqOr1>NONE</PromotionPrereqOr1>")

		if(objPromotionInfo.getPrereqOrPromotion2() != -1):
			szText = appendString(szText,"			<PromotionPrereqOr2>%s</PromotionPrereqOr2>" %(gc.getPromotionInfo(objPromotionInfo.getPrereqOrPromotion2()).getType()))
		else:
			szText = appendString(szText,"			<PromotionPrereqOr2>NONE</PromotionPrereqOr2>")

		if(objPromotionInfo.getTechPrereq() != -1):
			szText = appendString(szText,"			<TechPrereq>%s</TechPrereq>" %(gc.getTechInfo(objPromotionInfo.getTechPrereq()).getType()))
		else:
			szText = appendString(szText,"			<TechPrereq>NONE</TechPrereq>")

		szText = appendString(szText,"			<bLeader>%s</bLeader>" %(boolToInt(objPromotionInfo.isLeader())))
		szText = appendString(szText,"			<bBlitz>%s</bBlitz>" %(boolToInt(objPromotionInfo.isBlitz())))
		szText = appendString(szText,"			<bAmphib>%s</bAmphib>" %(boolToInt(objPromotionInfo.isAmphib())))
		szText = appendString(szText,"			<bRiver>%s</bRiver>" %(boolToInt(objPromotionInfo.isRiver())))
		szText = appendString(szText,"			<bEnemyRoute>%s</bEnemyRoute>" %(boolToInt(objPromotionInfo.isEnemyRoute())))
		szText = appendString(szText,"			<bAlwaysHeal>%s</bAlwaysHeal>" %(boolToInt(objPromotionInfo.isAlwaysHeal())))
		szText = appendString(szText,"			<bHillsDoubleMove>%s</bHillsDoubleMove>" %(boolToInt(objPromotionInfo.isHillsDoubleMove())))
		szText = appendString(szText,"			<bImmuneToFirstStrikes>%s</bImmuneToFirstStrikes>" %(boolToInt(objPromotionInfo.isImmuneToFirstStrikes())))
		
		
		szText = appendString(szText,"			<iVisibilityChange>%s</iVisibilityChange>" %(objPromotionInfo.getVisibilityChange()))
		szText = appendString(szText,"			<iMovesChange>%s</iMovesChange>" %(objPromotionInfo.getMovesChange()))
		szText = appendString(szText,"			<iMoveDiscountChange>%s</iMoveDiscountChange>" %(objPromotionInfo.getMoveDiscountChange()))
		szText = appendString(szText,"			<iWithdrawalChange>%s</iWithdrawalChange>" %(objPromotionInfo.getWithdrawalChange()))
		szText = appendString(szText,"			<iCollateralDamageChange>%s</iCollateralDamageChange>" %(objPromotionInfo.getCollateralDamageChange()))
		szText = appendString(szText,"			<iBombardRateChange>%s</iBombardRateChange>" %(objPromotionInfo.getBombardRateChange()))
		szText = appendString(szText,"			<iFirstStrikesChange>%s</iFirstStrikesChange>" %(objPromotionInfo.getFirstStrikesChange()))
		szText = appendString(szText,"			<iChanceFirstStrikesChange>%s</iChanceFirstStrikesChange>" %(objPromotionInfo.getChanceFirstStrikesChange()))
		szText = appendString(szText,"			<iEnemyHealChange>%s</iEnemyHealChange>" %(objPromotionInfo.getEnemyHealChange()))
		szText = appendString(szText,"			<iNeutralHealChange>%s</iNeutralHealChange>" %(objPromotionInfo.getNeutralHealChange()))
		szText = appendString(szText,"			<iFriendlyHealChange>%s</iFriendlyHealChange>" %(objPromotionInfo.getFriendlyHealChange()))
		szText = appendString(szText,"			<iSameTileHealChange>%s</iSameTileHealChange>" %(objPromotionInfo.getSameTileHealChange()))
		szText = appendString(szText,"			<iAdjacentTileHealChange>%s</iAdjacentTileHealChange>" %(objPromotionInfo.getAdjacentTileHealChange()))
		szText = appendString(szText,"			<iCombatPercent>%s</iCombatPercent>" %(objPromotionInfo.getCombatPercent()))
		szText = appendString(szText,"			<iCityAttack>%s</iCityAttack>" %(objPromotionInfo.getCityAttackPercent()))
		szText = appendString(szText,"			<iCityDefense>%s</iCityDefense>" %(objPromotionInfo.getCityDefensePercent()))
		szText = appendString(szText,"			<iHillsAttack>%s</iHillsAttack>" %(objPromotionInfo.getHillsAttackPercent()))
		szText = appendString(szText,"			<iHillsDefense>%s</iHillsDefense>" %(objPromotionInfo.getHillsDefensePercent()))
		szText = appendString(szText,"			<iKamikazePercent>%s</iKamikazePercent>" %(objPromotionInfo.getKamikazePercent()))
		szText = appendString(szText,"			<iRevoltProtection>%s</iRevoltProtection>" %(objPromotionInfo.getRevoltProtection()))
		szText = appendString(szText,"			<iCollateralDamageProtection>%s</iCollateralDamageProtection>" %(objPromotionInfo.getCollateralDamageProtection()))
		szText = appendString(szText,"			<iPillageChange>%s</iPillageChange>" %(objPromotionInfo.getPillageChange()))
		szText = appendString(szText,"			<iUpgradeDiscount>%s</iUpgradeDiscount>" %(objPromotionInfo.getUpgradeDiscount()))
		szText = appendString(szText,"			<iExperiencePercent>%s</iExperiencePercent>" %(objPromotionInfo.getExperiencePercent()))

		if(self.isTerrainDefenseDefined(iPromotion)):
			szText = appendString(szText,"			<TerrainDefenses>")
			for iI in range(gc.getNumTerrainInfos()):
				if(objPromotionInfo.getTerrainDefensePercent(iI) > 0):
					szText = appendString(szText,"				<TerrainDefense>")
					szText = appendString(szText,"					<TerrainType>%s</TerrainType>" %(gc.getTerrainInfo(iI).getType()))
					szText = appendString(szText,"					<iTerrainDefense>%s</iTerrainDefense>" %(objPromotionInfo.getTerrainDefensePercent(iI)))
					szText = appendString(szText,"				</TerrainDefense>")
				
			szText = appendString(szText,"			</TerrainDefenses>")
		else:
			szText = appendString(szText,"			<TerrainDefenses/>")
			
		if(self.isFeatureDefenseDefined(iPromotion)):
			szText = appendString(szText,"			<FeatureDefenses>")
			for iI in range(gc.getNumFeatureInfos()):
				if(objPromotionInfo.getFeatureDefensePercent(iI) > 0):
					szText = appendString(szText,"				<FeatureDefense>")
					szText = appendString(szText,"					<FeatureType>%s</FeatureType>" %(gc.getFeatureInfo(iI).getType()))
					szText = appendString(szText,"					<iFeatureDefense>%s</iFeatureDefense>" %(objPromotionInfo.getFeatureDefensePercent(iI)))
					szText = appendString(szText,"				</FeatureDefense>")
				
			szText = appendString(szText,"			</FeatureDefenses>")
		else:
			szText = appendString(szText,"			<FeatureDefenses/>")
			
		if(self.isUnitCombatModifierDefined(iPromotion)):
			szText = appendString(szText,"			<UnitCombatMods>")
			for iI in range(gc.getNumUnitCombatInfos()):
				if(objPromotionInfo.getUnitCombatModifierPercent(iI) > 0):
					szText = appendString(szText,"				<UnitCombatMod>")
					szText = appendString(szText,"					<UnitCombatType>%s</UnitCombatType>" %(gc.getUnitCombatInfo(iI).getType()))
					szText = appendString(szText,"					<iUnitCombatMod>%s</iUnitCombatMod>" %(objPromotionInfo.getUnitCombatModifierPercent(iI)))
					szText = appendString(szText,"				</UnitCombatMod>")
				
			szText = appendString(szText,"			</UnitCombatMods>")
		else:
			szText = appendString(szText,"			<UnitCombatMods/>")

		if(self.isDomainModifierDefined(iPromotion)):
			szText = appendString(szText,"			<DomainMods>")
			for iI in range(DomainTypes.NUM_DOMAIN_TYPES):
				if(objPromotionInfo.getDomainModifierPercent(iI) > 0):
					szText = appendString(szText,"				<DomainMod>")
					szText = appendString(szText,"					<DomainType>%s</DomainType>" %(gc.getDomainInfo(iI).getType()))
					szText = appendString(szText,"					<iDomainMod>%s</iDomainMod>" %(objPromotionInfo.getDomainModifierPercent(iI)))
					szText = appendString(szText,"				</DomainMod>")
				
			szText = appendString(szText,"			</DomainMods>")
		else:
			szText = appendString(szText,"			<DomainMods/>")

		if(self.isTerrainDoubleMoveDefined(iPromotion)):
			szText = appendString(szText,"			<TerrainDoubleMoves>")
			for iI in range(gc.getNumTerrainInfos()):
				if(objPromotionInfo.getTerrainDoubleMove(iI)):
					szText = appendString(szText,"				<TerrainDoubleMove>")
					szText = appendString(szText,"					<TerrainType>%s</TerrainType>" %(gc.getTerrainInfo(iI).getType()))
					szText = appendString(szText,"					<bTerrainDoubleMove>1</bTerrainDoubleMove>")
					szText = appendString(szText,"				</TerrainDoubleMove>")
				
			szText = appendString(szText,"			</TerrainDoubleMoves>")
		else:
			szText = appendString(szText,"			<TerrainDoubleMoves/>")
			
		if(self.isFeatureDoubleMoveDefined(iPromotion)):
			szText = appendString(szText,"			<FeatureDoubleMoves>")
			for iI in range(gc.getNumFeatureInfos()):
				if(objPromotionInfo.getFeatureDoubleMove(iI)):
					szText = appendString(szText,"				<FeatureDoubleMove>")
					szText = appendString(szText,"					<FeatureType>%s</FeatureType>" %(gc.getFeatureInfo(iI).getType()))
					szText = appendString(szText,"					<bFeatureDoubleMove>1</bFeatureDoubleMove>")
					szText = appendString(szText,"				</FeatureDoubleMove>")
				
			szText = appendString(szText,"			</FeatureDoubleMoves>")
		else:
			szText = appendString(szText,"			<FeatureDoubleMoves/>")

		if(self.isUnitCombatDefined(iPromotion)):
			szText = appendString(szText,"			<UnitCombats>")
			for iI in range(gc.getNumUnitCombatInfos()):
				if(objPromotionInfo.getUnitCombat(iI)):
					szText = appendString(szText,"				<UnitCombat>")
					szText = appendString(szText,"					<UnitCombatType>%s</UnitCombatType>" %(gc.getUnitCombatInfo(iI).getType()))
					szText = appendString(szText,"					<bUnitCombat>1</bUnitCombat>")
					szText = appendString(szText,"				</UnitCombat>")
				
			szText = appendString(szText,"			</UnitCombats>")
		else:
			szText = appendString(szText,"			<UnitCombats/>")

		if(len(objPromotionInfo.getHotKey()) > 0):
			szText = appendString(szText,"			<HotKey>%s</HotKey>" %(objPromotionInfo.getHotKey()))
		else:
			szText = appendString(szText,"			<HotKey/>")
		
		szText = appendString(szText,"			<bAltDown>%s</bAltDown>" %(boolToInt(objPromotionInfo.isAltDown())))
		szText = appendString(szText,"			<bShiftDown>%s</bShiftDown>" %(boolToInt(objPromotionInfo.isShiftDown())))
		szText = appendString(szText,"			<bCtrlDown>%s</bCtrlDown>" %(boolToInt(objPromotionInfo.isCtrlDown())))
		szText = appendString(szText,"			<iHotKeyPriority>%s</iHotKeyPriority>" %(objPromotionInfo.getHotKeyPriority()))
		szText = appendString(szText,"			<Button>%s</Button>" %(objPromotionInfo.getButton()))
		if(objPromotionInfo.getOrderPriority() != 5):
			szText = appendString(szText,"			<iOrderPriority>%s</iOrderPriority>" %(objPromotionInfo.getOrderPriority()))

		szText = appendString(szText,"		</PromotionInfo>")

		
			
		return szText

						
	def printPromotions(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Units" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4PromotionInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Promotion Infos -->")
		szText = appendString(szText,"<Civ4PromotionInfos xmlns=\"x-schema:CIV4UnitSchema.xml\">")
		szText = appendString(szText,"	<PromotionInfos>")
				
		for iPromotion in range(gc.getNumPromotionInfos()):

			if(gc.getPromotionInfo(iPromotion).isDeleted()):
				continue

			szText = appendString(szText,self.printPromotion(iPromotion))
			
						
		szText = appendString(szText,"	</PromotionInfos>")
		szText = appendString(szText,"</Civ4PromotionInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Units")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Units\CIV4PromotionInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
				
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

